package com.wujunshen.rest.web.controller;

import com.wujunshen.core.bean.ID;
import com.wujunshen.core.bean.IdMeta;
import com.wujunshen.core.service.IdService;
import com.wujunshen.rest.bean.MakeID;
import com.wujunshen.rest.bean.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Api("ID生成器")
@Slf4j
@RestController
public class IDGenerateController {

    @Resource
    private IdService idService;

    @GetMapping(value = "/genid")
    @ApiOperation(value = "生成ID", httpMethod = "GET", notes = "成功返回ID", response = ResponseResult.class)
    public ResponseResult genId() {
        return ResponseResult.success(idService.genId());
    }

    @GetMapping("/explainid/{id:[0-9]*}")
    @ApiOperation(value = "对ID进行解析", httpMethod = "GET", notes = "成功返回解析后的ID（json格式）", response = ID.class)
    public ResponseResult explainId(@ApiParam(value = "要解析的ID", required = true) @PathVariable("id") long id) {
        ID bean = idService.expId(id);
        bean.setTimeStamp(bean.getTimeStamp() + IdMeta.START_TIME); //毫秒数
        return ResponseResult.success(bean);
    }

    @PostMapping("/makeid")
    @ApiOperation(value = "生成ID", httpMethod = "POST", notes = "成功返回ID", response = long.class)
    public ResponseResult makeID(@ApiParam(value = "传入的相应参数（json格式）", required = true) @RequestBody MakeID makeID) {
        long worker = makeID.getMachine();
        long time = makeID.getTime();
        long sequence = makeID.getSeq();
        log.info("worker {} time {} sequence {}", worker, time, sequence);
        if (time == -1 || sequence == -1) {
            return ResponseResult.error("Both time and sequence are required.");
        }
        if (worker == -1) {
            return ResponseResult.error("worker and sequence are required.");
        } else {
            return ResponseResult.success(idService.makeId(time, worker, sequence));
        }
    }

}
